﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Epam.PhotoGallery.Interfaces.Providers;
using Epam.PhotoGallery.Bussines.Providers;
using Epam.PhotoGallery.Site.Models;
using Epam.PhotoGallery.Interfaces.DataTransferObjects;


namespace Epam.PhotoGallery.Site.Controllers
{
    [HandleError( View="LibraryError")]
    public class LibraryController : Controller
    {   
        #region Constants

        private const string BOOK_DETAILS_VIEW_NAME = "BookDetails";
        private const string CURRENT_PAGE_PARAM_NAME = "currentPage";
        private const string TOTAL_PAGES_PARAM_NAME = "totalPages";

        private const int DEFAULT_PAGE_SIZE = 10;


        #endregion

        #region Fields

        ILibraryDataProvider _provider;

        #endregion

        #region Properties

        /// <summary>
		/// Gets the data provider.
	    /// </summary>
        public ILibraryDataProvider DataProvider
        {
            get
            {
                if (_provider == null)
                {
                    _provider = new OfficeLibraryDataProvider();
                }

                return _provider;
            }
        }

        /// <summary>
        /// Gets or sets the book's count per page
        /// </summary>
        public int PageSize
        { get; set; }


        /// <summary>
        /// Gets or sets the model.
        /// </summary>
        /// <value>
        /// The model.
        /// </value>
        public OfficeLibrary Model { get; set; }

        #endregion

        #region Constructors

        public LibraryController()
        {
            PageSize = DEFAULT_PAGE_SIZE;
        }

        #endregion


        /// <summary>
        /// Gets books associate with current page.
        /// </summary>
        /// <returns>
        /// Return books from library.
        /// </returns>
        public ViewResult Index(int page)
        {
            var result = OfficeLibrary.GetModel(this.DataProvider);

            ViewData[CURRENT_PAGE_PARAM_NAME] = page;
            ViewData[TOTAL_PAGES_PARAM_NAME] = (int)Math.Ceiling((double)result.LibraryBooks.Count() / PageSize);

            return View(result.LibraryBooks.Skip(PageSize*(page-1)).Take(PageSize));
        }

        /// <summary>
        /// Gets books details
        /// </summary>
        /// <returns>
        /// Return books details from library
        /// </returns>
        public ViewResult GetBookDetails(string isbnID)
        {
            BookDetails bookDetails = OfficeLibrary.GetBookDetails(isbnID);
            
            return View(BOOK_DETAILS_VIEW_NAME, bookDetails);
        }


    }
}
